package com.sanhe.rfmuscle.activity.work;

import static com.menu.app.util.FunctionCode.START1;
import static com.menu.app.util.FunctionCode.START2;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;

import com.menu.app.MyApp;
import com.menu.app.db.CusUsageDao;
import com.menu.app.db.CustomDao;
import com.menu.app.db.DBListener;
import com.menu.app.db.DocDao;
import com.menu.app.db.bean.Custom;
import com.menu.app.http.bean.ReportBean;
import com.menu.app.http.req.ReportReq;
import com.menu.app.it.ReqCallback;
import com.menu.app.util.port.SerialManage;
import com.plata.base.aclr.common.SilentTask;
import com.plata.base.aclr.common.TaskEngine;
import com.plata.base.aclr.utils.SPHelper;
import com.sanhe.rfmuscle.R;
import com.sanhe.rfmuscle.activity.BoardActivity;
import com.sanhe.rfmuscle.databinding.ActivityWorkBinding;
import com.sanhe.rfmuscle.event.Event;
import com.sanhe.rfmuscle.event.LeftBEvent;
import com.sanhe.rfmuscle.event.LeftProgressEvent;
import com.sanhe.rfmuscle.event.LeftRfEvent;
import com.sanhe.rfmuscle.event.LeftTimeEvent;
import com.sanhe.rfmuscle.event.Num1Event;
import com.sanhe.rfmuscle.event.P1ShowEvent;
import com.sanhe.rfmuscle.event.P2ShowEvent;
import com.sanhe.rfmuscle.event.RightBEvent;
import com.sanhe.rfmuscle.event.RightProgressEvent;
import com.sanhe.rfmuscle.event.RightRfEvent;
import com.sanhe.rfmuscle.event.TimeEvent;
import com.sanhe.rfmuscle.fragment.BodyFragment;
import com.sanhe.rfmuscle.fragment.ProFragment;
import com.sanhe.rfmuscle.util.Const;
import com.sanhe.rfmuscle.view.ArcSeekBar;
import com.sanhe.rfmuscle.view.LongClickImageView;
import com.sanhe.rfmuscle.view.TrapezoidSeekBar;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;

import java.util.HashMap;

import me.drakeet.support.toast.ToastUtil;

public class WorkActivity extends BaseWorkActivity {

    ActivityWorkBinding binding;
    private ProFragment proFragment = new ProFragment();
    private BodyFragment bodyFragment = new BodyFragment();

    Handler timerHandler = new Handler();
    Runnable timerRunnable;
    int timer = 0;
    private boolean showTotalTimer = false;

    Handler h = new Handler();
    Runnable runnable;

    String from;

    public void setFrom(String str) {
        from = str;
    }

    boolean isQuick = false;
    HashMap param;

    public void setQuick(boolean isQuick, HashMap param) {
        this.isQuick = isQuick;
        this.param = param;
    }

    private void setQuickParam() {
        if (!isQuick || param == null) {
            return;
        }
        showLoading();
        Log.e(TAG, "showLoading: ");
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                Thread.sleep(150);
                //切换time1
                try {
                    int p = Integer.valueOf(param.get("time1") + "");
                    Log.e(TAG, "切换time1: " + p);
                    byte[] tmp = {START1, START2, 6, (byte) 0x83, 0x11, 6, 1, 0, (byte) p};
                    SerialManage.getInstance().send(tmp);
                    Thread.sleep(150);
                } catch (Throwable e) {
                    e.printStackTrace();
                }
                //切换time2
                try {
                    int p = Integer.valueOf(param.get("time2") + "");
                    Log.e(TAG, "切换time2: " + p);
                    byte[] tmp = {START1, START2, 6, (byte) 0x83, 0x11, 7, 1, 0, (byte) p};
                    SerialManage.getInstance().send(tmp);
                    Thread.sleep(150);
                } catch (Throwable e) {
                    e.printStackTrace();
                }
                //切换flow1
                try {
                    int p = Integer.valueOf(param.get("fluence1") + "");
                    byte[] tmp = {START1, START2, 6, (byte) 0x83, 0x11, 0, 1, 0, (byte) p};
                    SerialManage.getInstance().send(tmp);
                    Thread.sleep(150);
                } catch (Throwable e) {
                    e.printStackTrace();
                }
                //切换flow2
                try {
                    int p = Integer.valueOf(param.get("fluence2") + "");
                    byte[] tmp = {START1, START2, 6, (byte) 0x83, 0x11, 5, 1, 0, (byte) p};
                    SerialManage.getInstance().send(tmp);
                    Thread.sleep(150);
                } catch (Throwable e) {
                    e.printStackTrace();
                }
                if (Const.mode == 3) {
                    //切换mf
                    try {
                        int mf = Integer.valueOf(param.get("mf") + "");
                        for (int i = 1; i < mf; i++) {
                            sendTouchEvent((byte) 0, (byte) 0x31);
                            Thread.sleep(150);
                        }
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                    //切换mt
                    try {
                        int mt = Integer.valueOf(param.get("mt") + "");
                        for (int i = 1; i < mt; i++) {
                            sendTouchEvent((byte) 0, (byte) 0x35);
                            Thread.sleep(150);
                        }
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                    //切换sf
                    try {
                        int sf = Integer.valueOf(param.get("sf") + "");
                        for (int i = 1; i < sf; i++) {
                            sendTouchEvent((byte) 0, (byte) 0x33);
                            Thread.sleep(150);
                            //50以后步进为5
                            if (i > 49) {
                                i = i + 4;
                            }
                        }
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                    //切换st
                    try {
                        int st = Integer.valueOf(param.get("st") + "");
                        for (int i = 1; i < st; i++) {
                            sendTouchEvent((byte) 0, (byte) 0x37);
                            Thread.sleep(150);
                        }
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                }
                if (Const.mode == 2) {
                    //切换rf1
                    try {
                        int rf1 = Integer.valueOf(param.get("rf1") + "");
                        for (int i = 0; i < rf1; i++) {
                            sendTouchEvent((byte) 0, (byte) 0x93);
                            Thread.sleep(150);
                        }
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                    //切换rf2
                    try {
                        int rf2 = Integer.valueOf(param.get("rf2") + "");
                        for (int i = 0; i < rf2; i++) {
                            sendTouchEvent((byte) 0, (byte) 0x91);
                            Thread.sleep(150);
                        }
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                }
                h.post(() -> hideLoading());
            }
        });
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityWorkBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setQuickParam();

        binding.leftSwitch.setOnClickListener(v -> {
            if (Event.leftBEvent.getValue() <= 0) {
                ToastUtil.showShortToast(this, R.string.muscle_handle_error);
            } else {
                if (Const.isSport) {
                    if (Event.p2WorkEvent.getValue() == 1) {
                        Event.leftTimeEvent.postValue(Event.timeEvent.getValue());
                    }
                }
                sendTouchEvent((byte) 0, (byte) 0x2c);
            }

        });

        binding.rightSwitch.setOnClickListener(v -> {
            if (Event.rightBEvent.getValue() <= 0) {
                ToastUtil.showShortToast(this, R.string.muscle_handle_error);
            } else {
                if (Const.isSport) {
                    if (Event.p1WorkEvent.getValue() == 1) {
                        Event.timeEvent.postValue(Event.leftTimeEvent.getValue());
                    }
                }
                sendTouchEvent((byte) 0, (byte) 0x2d);
            }
        });

        binding.leftArc.setOnProgressChangeListener(new ArcSeekBar.OnProgressChangeListener() {

            boolean isUser;

            @Override
            public void onProgressChanged(ArcSeekBar seekBar, int progress, boolean isUser) {
                this.isUser = isUser;
            }

            @Override
            public void onStartTrackingTouch(ArcSeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(ArcSeekBar seekBar) {
                if (!isUser) {
                    return;
                }
                int p = seekBar.getProgress();
                if (p >= 57) {
                    p = 60;
                } else if (p <= 2) {
                    p = 0;
                }
                byte[] tmp = {START1, START2, 6, (byte) 0x83, 0x11, 6, 1, 0, (byte) p};
                SerialManage.getInstance().send(tmp);
            }
        });
        binding.rightArc.setOnProgressChangeListener(new ArcSeekBar.OnProgressChangeListener() {

            boolean isUser;

            @Override
            public void onProgressChanged(ArcSeekBar seekBar, int progress, boolean isUser) {
                this.isUser = isUser;
            }

            @Override
            public void onStartTrackingTouch(ArcSeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(ArcSeekBar seekBar) {
                if (!isUser) {
                    return;
                }
                int p = seekBar.getProgress();
                if (p >= 57) {
                    p = 60;
                } else if (p <= 2) {
                    p = 0;
                }
                byte[] tmp = {START1, START2, 6, (byte) 0x83, 0x11, 7, 1, 0, (byte) p};
                SerialManage.getInstance().send(tmp);
            }
        });
//
//        binding.leftSeekBar.setOnProgressChangeListener(new TrapezoidSeekBar.OnProgressChangeListener() {
//
//            boolean isUser;
//
//            @Override
//            public void onProgressChanged(TrapezoidSeekBar seekBar, int progress, boolean isUser) {
//                this.isUser = isUser;
//            }
//
//            @Override
//            public void onStartTrackingTouch(TrapezoidSeekBar seekBar) {
//
//            }
//
//            @Override
//            public void onStopTrackingTouch(TrapezoidSeekBar seekBar) {
//                if (!isUser) {
//                    return;
//                }
//                int p = seekBar.getProgress();
//                if (p >= 97) {
//                    p = 100;
//                } else if (p <= 2) {
//                    p = 0;
//                }
//                byte[] tmp = {START1, START2, 6, (byte) 0x83, 0x11, 0, 1, 0, (byte) p};
//                SerialManage.getInstance().send(tmp);
//            }
//        });
//        binding.rightSeekBar.setOnProgressChangeListener(new TrapezoidSeekBar.OnProgressChangeListener() {
//
//            boolean isUser;
//
//            @Override
//            public void onProgressChanged(TrapezoidSeekBar seekBar, int progress, boolean isUser) {
//                this.isUser = isUser;
//            }
//
//            @Override
//            public void onStartTrackingTouch(TrapezoidSeekBar seekBar) {
//
//            }
//
//            @Override
//            public void onStopTrackingTouch(TrapezoidSeekBar seekBar) {
//                if (!isUser) {
//                    return;
//                }
//                int p = seekBar.getProgress();
//                if (p >= 97) {
//                    p = 100;
//                } else if (p <= 2) {
//                    p = 0;
//                }
//                byte[] tmp = {START1, START2, 6, (byte) 0x83, 0x11, 5, 1, 0, (byte) p};
//                SerialManage.getInstance().send(tmp);
//            }
//        });
        binding.leftSeekBar.setEnabled(false);
        binding.rightSeekBar.setEnabled(false);

        binding.leftTimerReduce.setLongClickListener(new LongClickImageView.LongClickListener() {
            @Override
            public void onActionDown() {
                startHandler((byte) 1, (byte) 0x22);
            }

            @Override
            public void onActionUp() {
                stopHandler();
                if (Const.jump2) {
                    int n = Event.leftTimeEvent.getValue();
                    n = Math.max(n - 10, 0);
                    Event.leftTimeEvent.postValue(n);
                }
            }
        });

        binding.leftTimerAdd.setLongClickListener(new LongClickImageView.LongClickListener() {
            @Override
            public void onActionDown() {
                startHandler((byte) 1, (byte) 0x23);
            }

            @Override
            public void onActionUp() {
                stopHandler();
                if (Const.jump2) {
                    int n = Event.leftTimeEvent.getValue();
                    n = Math.min(n + 10, 60);
                    Event.leftTimeEvent.postValue(n);
                }
            }
        });

        binding.rightTimerReduce.setLongClickListener(new LongClickImageView.LongClickListener() {
            @Override
            public void onActionDown() {
                startHandler((byte) 1, (byte) 0x24);
            }

            @Override
            public void onActionUp() {
                stopHandler();
                if (Const.jump2) {
                    int n = Event.timeEvent.getValue();
                    n = Math.max(n - 10, 0);
                    Event.timeEvent.postValue(n);
                }
            }
        });

        binding.rightTimerAdd.setLongClickListener(new LongClickImageView.LongClickListener() {
            @Override
            public void onActionDown() {
                startHandler((byte) 1, (byte) 0x25);
            }

            @Override
            public void onActionUp() {
                stopHandler();
                if (Const.jump2) {
                    int n = Event.timeEvent.getValue();
                    n = Math.min(n + 10, 60);
                    Event.timeEvent.postValue(n);
                }
            }
        });

        binding.leftEnergyAdd.setLongClickListener(new LongClickImageView.LongClickListener() {
            @Override
            public void onActionDown() {
                startHandler((byte) 1, (byte) 0x29);
            }

            @Override
            public void onActionUp() {
                stopHandler();
                if (Const.jump2) {
                    int n = Event.leftProgressEvent.getValue();
                    n = Math.min(n + 10, 100);
                    Event.leftProgressEvent.postValue(n);
                }
            }
        });

        binding.leftEnergyReduce.setLongClickListener(new LongClickImageView.LongClickListener() {
            @Override
            public void onActionDown() {
                startHandler((byte) 1, (byte) 0x28);
            }

            @Override
            public void onActionUp() {
                stopHandler();
                if (Const.jump2) {
                    int n = Event.leftProgressEvent.getValue();
                    n = Math.max(n - 10, 0);
                    Event.leftProgressEvent.postValue(n);
                }
            }
        });

        binding.rightEnergyAdd.setLongClickListener(new LongClickImageView.LongClickListener() {
            @Override
            public void onActionDown() {
                startHandler((byte) 1, (byte) 0x2b);
            }

            @Override
            public void onActionUp() {
                stopHandler();
                if (Const.jump2) {
                    int n = Event.rightProgressEvent.getValue();
                    n = Math.min(n + 10, 100);
                    Event.rightProgressEvent.postValue(n);
                }
            }
        });

        binding.rightEnergyReduce.setLongClickListener(new LongClickImageView.LongClickListener() {
            @Override
            public void onActionDown() {
                startHandler((byte) 1, (byte) 0x2a);
            }

            @Override
            public void onActionUp() {
                stopHandler();
                if (Const.jump2) {
                    int n = Event.rightProgressEvent.getValue();
                    n = Math.max(n - 10, 0);
                    Event.rightProgressEvent.postValue(n);
                }
            }
        });
        binding.leftRfReduce.setLongClickListener(new LongClickImageView.LongClickListener() {
            @Override
            public void onActionDown() {
                startHandler((byte) 1, (byte) 0x92);
            }

            @Override
            public void onActionUp() {
                stopHandler();

            }
        });
        binding.leftRfAdd.setLongClickListener(new LongClickImageView.LongClickListener() {
            @Override
            public void onActionDown() {
                startHandler((byte) 1, (byte) 0x93);
            }

            @Override
            public void onActionUp() {
                stopHandler();

            }
        });
        binding.rightRfReduce.setLongClickListener(new LongClickImageView.LongClickListener() {
            @Override
            public void onActionDown() {
                startHandler((byte) 1, (byte) 0x90);
            }

            @Override
            public void onActionUp() {
                stopHandler();

            }
        });
        binding.rightRfAdd.setLongClickListener(new LongClickImageView.LongClickListener() {
            @Override
            public void onActionDown() {
                startHandler((byte) 1, (byte) 0x91);
            }

            @Override
            public void onActionUp() {
                stopHandler();

            }
        });

        binding.timer.setOnClickListener(v -> {
            if (showTotalTimer) {
                showTotalTimer = false;
                updateTimerUI();
            } else {
                showTotalTimer = true;
                updateTimerUI();
            }
        });

        initMode();

        updateLeftTime();
        updateRightTime();

        updateTimerUI();

        updateLeftProgress();
        updateRightProgress();

        updateP1();
        updateP2();

        updateLeftRf();
        updateRightRf();

        updateDisconnect();

        binding.title.setText(getModeTitle());
        binding.back.setOnClickListener(v -> {
            dealBack();
            if (Const.jump) {
                finish();
            }
        });
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LeftBEvent event) {
        updateDisconnect();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RightBEvent event) {
        updateDisconnect();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LeftProgressEvent event) {
        updateLeftProgress();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RightProgressEvent event) {
        updateRightProgress();
    }

    private void updateLeftProgress() {
        int n = Event.leftProgressEvent.getValue();
        binding.leftEnergy.setText(n + "");
        binding.leftSeekBar.setProgress(n);
    }

    private void updateRightProgress() {
        int n = Event.rightProgressEvent.getValue();
        binding.rightEnergy.setText(n + "");
        binding.rightSeekBar.setProgress(n);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TimeEvent event) {
        updateRightTime();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LeftTimeEvent event) {
        updateLeftTime();
    }

    private void updateLeftTime() {
        int n = Event.leftTimeEvent.getValue();
        binding.leftArc.setProgress(n);
        binding.leftTime.setText(Event.leftTimeEvent.getValue() + "");

        if (Event.p1WorkEvent.getValue() == 1) {
            Const.totalTimer++;
            Const.usedTimer++;
            SPHelper.getInstance(MyApp.getApp()).putInt(Const.TOTAL_TIMER, Const.totalTimer).commit();
            updateTimerUI();
        }
    }

    private void updateRightTime() {
        int n = Event.timeEvent.getValue();
        binding.rightArc.setProgress(n);
        binding.rightTime.setText(Event.timeEvent.getValue() + "");

        if (Event.p1WorkEvent.getValue() != 1 && Event.p2WorkEvent.getValue() == 1) {
            Const.totalTimer++;
            Const.usedTimer++;
            SPHelper.getInstance(MyApp.getApp()).putInt(Const.TOTAL_TIMER, Const.totalTimer).commit();
            updateTimerUI();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(LeftRfEvent event) {
        updateLeftRf();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(RightRfEvent event) {
        updateRightRf();
    }

    private void updateLeftRf() {
        binding.leftRf.setText(Event.leftRfEvent.getValue() + "");
    }

    private void updateRightRf() {
        binding.rightRf.setText(Event.rightRfEvent.getValue() + "");
    }


    private void initMode() {
        if (Const.mode == 1) {
            //运动模式，没有时间调节，rf调节
            binding.rfCtrl.setVisibility(View.GONE);
            binding.rfCtrl2.setVisibility(View.GONE);
            binding.leftTimerAdd.setVisibility(View.INVISIBLE);
            binding.leftTimerReduce.setVisibility(View.INVISIBLE);
            binding.rightTimerAdd.setVisibility(View.INVISIBLE);
            binding.rightTimerReduce.setVisibility(View.INVISIBLE);
            binding.leftArc.setEnabled(false);
            binding.rightArc.setEnabled(false);
        } else {
            if (Event.rfShowEvent.getValue() == 0) {
                binding.rfCtrl.setVisibility(View.GONE);
                binding.rfCtrl2.setVisibility(View.GONE);
            }
        }

        initFragment();
    }

    long workPoint;
    private boolean started = false;
    private long startTime1;
    private long startTime2;

    private void updateWorking() {
        if (Event.p1WorkEvent.getValue() == 1 || Event.p2WorkEvent.getValue() == 1) {
            started = true;
        } else {
            started = false;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(P1ShowEvent event) {
        updateWorking();
        updateP1();
        if (event.getValue() == 0) {
            record(workPoint, System.currentTimeMillis() - startTime1);
            workPoint = 0;
            realExit();
        } else if (event.getValue() == 1) {
            startTime1 = System.currentTimeMillis();
        }
    }

    private void updateP1() {
        if (Event.p1WorkEvent.getValue() == 1) {
            binding.leftSwitch.setImageResource(R.mipmap.work_pause);
        } else {
            binding.leftSwitch.setImageResource(R.mipmap.work_start);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(P2ShowEvent event) {
        updateWorking();
        updateP2();
        if (event.getValue() == 0) {
            record(workPoint, System.currentTimeMillis() - startTime2);
            workPoint = 0;
            if (exit) {
                if (Event.p1WorkEvent.getValue() == 1) {
                    TaskEngine.getInstance().submit(new SilentTask("") {
                        @Override
                        public void runInBackground() throws Exception {
                            Thread.sleep(200);
                            sendTouchEvent((byte) 0, (byte) 0x2c);
                        }
                    });
                } else {
                    realExit();
                }
            }
        } else if (event.getValue() == 1) {
            startTime2 = System.currentTimeMillis();
        }
    }

    private void updateP2() {
        if (Event.p2WorkEvent.getValue() == 1) {
            binding.rightSwitch.setImageResource(R.mipmap.work_pause);
        } else {
            binding.rightSwitch.setImageResource(R.mipmap.work_start);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Num1Event event) {
        if (started) {
            ++workPoint;
        }
    }


    private void record(long point, long time) {
        if (BoardActivity.custom != null) {
            BoardActivity.custom.num += point;
            new CustomDao().updateCount(BoardActivity.custom, null);
        }
        try {
            insert(point, time);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        if (MyApp.getApp().getDoc() != null) {
            MyApp.getApp().getDoc().num += point;
            new DocDao().updateCount(MyApp.getApp().getDoc(), null);
        }
    }

    CusUsageDao dao;

    private void insert(long point, long time) throws JSONException {
        Custom usr = BoardActivity.custom;
        HashMap param = new HashMap();
        param.put("mode", Const.mode + "");
        param.put("time1", Event.leftTimeEvent.getValue() + "");
        param.put("fluence1", Event.leftProgressEvent.getValue() + "");
        param.put("time2", Event.timeEvent.getValue() + "");
        param.put("fluence2", Event.rightProgressEvent.getValue() + "");
        if (Const.mode != 1) {
            param.put("rf1", Event.leftRfEvent.getValue() + "");
            param.put("rf2", Event.rightRfEvent.getValue() + "");
        }
        if (Const.mode == 3) {
            param.put("mf", Event.mfEvent.getValue() + "");
            param.put("mt", Event.mtEvent.getValue() + "");
            param.put("sf", Event.sfEvent.getValue() + "");
            param.put("st", Event.stEvent.getValue() + "");
        }
        param.put("time", time + "");
        if (dao == null) {
            dao = new CusUsageDao();
        }
        dao.insert(point, usr, 0, param, new DBListener() {
            @Override
            public void onResult(boolean bo, String msg, Object result) {
                if (bo) {
                    param.put("point", point + "");
                    new ReportReq(param, usr == null ? "" : usr.serverId, Const.HISTORY).req(new ReqCallback<ReportBean>() {
                        @Override
                        public void callback(boolean success, ReportBean bean) {
                            if (success && bean != null && bean.isValid()) {
                                Log.e(TAG, "callback: success");
                                dao.updateFlag((Long) result, null);
                            }
                        }
                    });
                }
            }
        });
    }

    private void updateTimerUI() {
        if (showTotalTimer) {
            binding.timer.setText(getTimerString(Const.totalTimer));
        } else {
            binding.timer.setText(getTimerString(Const.usedTimer));
        }
    }

    @Override
    public void onDestroy() {
        if (timerRunnable != null) timerHandler.removeCallbacksAndMessages(null);
        if (h != null) h.removeCallbacksAndMessages(null);
        super.onDestroy();
    }


    boolean exit = false;
    JumpPrepareListener jumpPrepareListener = null;

    @Override
    public void beforeJump(JumpPrepareListener listener) {
        if (isWorking()) {
            return;
        }
        exit = true;
        jumpPrepareListener = listener;
        realExit();
    }

    private void realExit() {
        if (!exit) {
            return;
        }
        super.beforeJump(jumpPrepareListener);
        finish();
    }


    private void initFragment() {
        if (Const.mode == 1 || Const.mode == 2) {
            addFragment(R.id.container, bodyFragment);
        } else if (Const.mode == 3) {
            addFragment(R.id.container, proFragment);
        }
    }

    private String getModeTitle() {
        if (Const.mode == 1) {
            return getString(R.string.sport);
        } else if (Const.mode == 2) {
            return getString(R.string.gentle);
        } else if (Const.mode == 3) {
            return getString(R.string.pro);
        }
        return "";
    }

    protected void dealBack() {
        if (isWorking()) {
            return;
        }
        if (fromCustom()) {
            MyApp.getApp().setIgnore(true);
            finish();
            return;
        }
        sendTouchEvent((byte) 0, (byte) 0x20);
    }

    public boolean fromCustom() {
        Class c = MyApp.getApp().getCustomInfoClass();
        if (c == null) {
            return false;
        }
        return c.getSimpleName().equals(from);
    }

    private boolean isWorking() {
        return Event.p1WorkEvent.getValue() == 1 || Event.p2WorkEvent.getValue() == 1;
    }

    private void startHandler(byte data_H, byte data_L) {
        if (runnable != null) h.removeCallbacks(runnable);
        runnable = new Runnable() {
            @Override
            public void run() {
                sendTouchEvent((byte) data_H, (byte) data_L);
                h.postDelayed(runnable, 200);
            }
        };
        h.post(runnable);

    }

    private void stopHandler() {
        h.removeCallbacks(runnable);
    }


    private String getTimerString(int timer) {
        int days = timer / (60 * 24);
        long hours = timer / 60 - days * 24;
        long minutes = timer - days * 24 * 60 - hours * 60;
        return String.format("%02d", days) + "d " + String.format("%02d", hours)
                + "h " + String.format("%02d", minutes) + "m";
    }

    private void updateDisconnect() {
        if (Event.leftBEvent.getValue() <= 0) {
            binding.leftDisconnect.setVisibility(View.VISIBLE);
        } else {
            binding.leftDisconnect.setVisibility(View.GONE);
        }
        if (Event.rightBEvent.getValue() <= 0) {
            binding.rightDisconnect.setVisibility(View.VISIBLE);
        } else {
            binding.rightDisconnect.setVisibility(View.GONE);
        }
    }

}
